import {Menu,Icon} from 'antd'
import React from 'react'
import Http from './Http'

function parseMenu(menus, parent = '#') {
    let authButton = []
    return  menus.map((item) => {
        if(item.childs.length > 0) {
            let menuChild = parseMenu(item.childs, `${parent}${item.rule}`);
            return (
                <Menu.SubMenu
                  title={item.name}
                  key={`${parent}${item.rule}${item.data}`}
                >
                    {menuChild}
                </Menu.SubMenu>
            )
        }else {
            authButton = item.buttons
            return (
                <Menu.Item key={`${parent}${item.rule}${item.data}`}>
                    <a
                      href={item.rule + (item.data === ''||item.data === '#'?'':('?'+item.data))}>
                        <Icon type={item.icon}/>
                        {item.name}
                    </a>
                </Menu.Item>)
        }
    })
}
@Http(
    {url:'/api/menu'},
    (res) => {
        if(res.code === 0 || res.code === '0') {
            return {menus: res.data.menus}
        }else if(res.code === -401 || res.code === '-401') {
            window.location.href = '/login'
        }else {
            return {menus:[]}
        }
    },
    <Menu mode="inline" style={{height:"100%"}} theme="dark"/>)
export default class Nav extends React.Component{
    constructor(props) {
        super(props)
    }


    render() {
        let { menus,selected } = this.props;
        let menuItems = parseMenu(menus, '');
        const openKeys = selected.split('/');
        return (
            <Menu
              mode="inline"
              selectedKeys={[selected]}
              style={{height:"100%"}}
              theme="dark"
              defaultOpenKeys={[openKeys[0]]}

            >
                {menuItems}
            </Menu>
        )
    }
}
